package cloud.lysky.java.on.concurrent.cas;

import sun.misc.Unsafe;

import javax.swing.text.html.parser.Entity;

/**
 * @author luoly
 * @describe
 * @date 2022-10-21 21:46
 **/
public class CASTest {
    public static void main(String[] args) throws NoSuchFieldException {
        A a = new A();
        Unsafe unsafe = UnsafeFactory.getUnsafe();
        //获取A中x字段的偏移量，便于后继根据偏移量找到x的内存地址进而找到x的值
        long offset = unsafe.objectFieldOffset(a.getClass().getDeclaredField("x"));
        boolean successful;

        //4个参数分别是:对象实例、字段的内存偏移量、字段期望值、字段新值
        //1.将x改为3(成功，因为x原来的值为0 这里提供的期望值也是0 所以一比较相等，然后把3赋值给x)
        successful = unsafe.compareAndSwapInt(a,offset,0,3);
        System.out.println("successful:" + successful + ", x =" + a.x);
        //2.将x改为5(成功，因为x的值在上面被改为3 这里提供的期望值也是3 所以一比较相等，然后把5赋值给x)
        successful = unsafe.compareAndSwapInt(a, offset, 3, 5);
        System.out.println("successful:" + successful + ", x =" + a.x);
        //3.将x改为8(失败，因为期望值传递的是3，而当前x已经改成5了 一比较，不相等就不赋值了)
        successful = unsafe.compareAndSwapInt(a,offset,3,8);
        System.out.println("successful:" + successful + ", x =" + a.x);
    }
}
//测试对象
class A{
    int x;
}